/**
 * 组件配置合并，xvue传过来的对象，在数组处理上通过lodash的merge方法处理，导致数组类型的属性会无法跟数据库一致
 * 需要重新处理
 * ------------------------
 */
import { mergeObj, clone, isObject, isArray, objHas } from '@/utils/util';
import { merge as _merge } from 'lodash';

export default {

  // 数组下面的对象补充新增属性
  fixArrProps(obj, orgObj) {
    if (isObject(obj)) {
      for (const i in orgObj) {
        if (!objHas(obj, i)) {
          obj[i] = orgObj[i];
        } else {
          obj[i] = this.fixArrProps(obj[i], orgObj[i]);
        }
      }
    } else if (isArray(obj) && orgObj) {
      for (let i = 0; i < obj.length; i++) {
        obj[i] = this.fixArrProps(obj[i], orgObj[i]);
      }
    } else {}
    return obj;
  },

  mergeProperty(orgConfig, dbConfig) {
    const orgProperty = orgConfig.config.property;
    const dbProperty = (dbConfig.config && dbConfig.config.property) || {};
    let property = mergeObj({}, orgProperty, dbProperty);
    property = this.fixArrProps(property, orgProperty);
    return property;
  },

  mergeData(orgConfig, dbConfig) {
    const orgData = orgConfig.config.data || {};
    const dbData = (dbConfig.config && dbConfig.config.data) || {};
    let data = mergeObj({}, orgData, dbData);
    data = this.fixArrProps(data, orgData);
    return data;
  },

  mergeEvents(orgConfig, dbConfig) {
    const events = clone(orgConfig.events || []);
    if (!dbConfig.events) {
      return events;
    }

    // 老数据有可能有重复事件id，只取有配key的有效事件
    const dbEvents = (dbConfig.events || []).filter(n => n.key);
    if (dbEvents) {
      dbEvents.forEach(dbEvt => {
        const evt = events.find(n => n.id === dbEvt.id);
        if (evt) {
          _merge(evt, dbEvt);
        }
      });
    }
    return events;
  },

  mergeConfig(orgConfig, dbConfig) {
    const _orgConfig = clone(orgConfig);
    let config = _merge({}, _orgConfig, dbConfig || {});
    config.config.property = this.mergeProperty(_orgConfig, dbConfig);
    config.config.data = this.mergeData(_orgConfig, dbConfig);
    config.events = this.mergeEvents(_orgConfig, dbConfig);
    config = this.decodeSpecialChars(config);
    return config;
  },

  decodeSpecialChars(config) {
    let str = JSON.stringify(config);
    str = str.replace(/&hellip;/g, '…');
    str = str.replace(/&middot;/g, '·');
    str = str.replace(/&mdash;/g, '—');
    str = str.replace(/&ldquo;/g, '“');
    str = str.replace(/&rdquo;/g, '”');
    const _config = JSON.parse(str);
    return _config;
  },
};
